package com.cswnode.Controller.Advice;

import com.cswnode.Util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author csw
 * @create 2020/9/30 10:24
 */
//统一异常处理
@ControllerAdvice(annotations = Controller.class)//只对标注Controller注解的类进行处理
public class ExceptionAdvice {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({Exception.class})
    public void handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常" + e.getMessage());
        for (StackTraceElement element : e.getStackTrace()){
            logger.error(element.toString());
        }

        String header = request.getHeader("x-requested-with");
        //处理异步json请求
        if ("XMLHttpRequest".equals(header)){
            //设置返回的格式为一个普通的字符串
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter printWriter = response.getWriter();
            printWriter.write(CommunityUtil.getJsonString(1,"服务器异常！"));
        }else {//请求为网页请求
            response.sendRedirect(request.getContextPath()+"/error");
        }
    }

}
